﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SpectationClient.SpectralTools;
using SpectationClient.DataBaseDescription;
using SpectationClient.DGVExtensions;

namespace SpectationClient {
    public partial class SaveDGV : Form {
        private DataGridView DGV;
        private String sep = "\relatedColumnType";
        private String filename = "attributes.csv";
        private String tablename;
        private List<String> id_columns;
        private bool excludeBLOBs;
        DataTable dtsep = new DataTable();


        public SaveDGV(ref DataGridView dgv, String tablename, bool excludeBlobs) {
            InitializeComponent();
            this.Icon = Resources.Icon;
            this.DGV = dgv;
            this.id_columns = new List<String>();
            this.tablename = tablename;
            this.filename = tablename.Replace('.', '_') + ".csv";
            this.excludeBLOBs = excludeBlobs;
            myinit();
        }

        public SaveDGV(ref DataGridView dgv, List<String> id_columns, String tablename, bool excludeBlobs) {
            InitializeComponent();
            this.Icon = Resources.Icon;
            this.DGV = dgv;
            this.id_columns = id_columns;
            this.tablename = tablename;
            this.filename = tablename.Replace('.', '_') + ".csv";
            this.excludeBLOBs = excludeBlobs;
            myinit();
        }

        public SaveDGV(ref DataGridView dgv, List<String> id_columns, String tablename, String headline, bool excludeBlobs) {
            InitializeComponent();
            this.Icon = Resources.Icon;
            this.Text = headline;
            this.DGV = dgv;
            this.id_columns = id_columns;
            this.tablename = tablename;
            this.filename = tablename.Replace('.', '_')+".csv";
            this.excludeBLOBs = excludeBlobs;
            myinit();
        }


        private void myinit() {
            dtsep.Columns.Add("SEP", typeof(String));
            dtsep.Columns.Add("SHOW", typeof(String));

            dtsep.Rows.Add(new object[] { "\relatedColumnType", "Tab" });
            dtsep.Rows.Add(new object[] { ";", ";" });
            dtsep.Rows.Add(new object[] { ",", "," });

            this.cB_sep.DataSource = dtsep;
            this.cB_sep.DisplayMember = "SHOW";
            this.cB_sep.ValueMember = "SEP";
        }

        private void btSetPath_Click(object sender, EventArgs e) {
            if (FBD.ShowDialog() == DialogResult.OK) {
                this.tbPath.Text = FBD.SelectedPath;
            }
        }

        private void btSave_Click(object sender, EventArgs e) {
            String basePath = tbPath.Text;
            StreamWriter sw = new StreamWriter(basePath + "\\" + filename, false, Encoding.Unicode);
            try {
                this.sep = cB_sep.SelectedValue.ToString();
                

                
                String colnames = "";
                String rowstring = "";
                String headline = "Tabelle:" + this.tablename;

                Dictionary<String, String> lut = new Dictionary<string, string>();

                //Write Column Names
                foreach (DataGridViewColumn c in DGV.Columns) {
                    if (c is DataGridViewSpectrumColumn) {
                        DataGridViewSpectrumColumn sc = (DataGridViewSpectrumColumn)c;
                        if (!lut.Keys.Contains<String>(sc.Name)) {
                            lut.Add(sc.Name, basePath + "\\" + sc.Name.Replace('.', '_'));
                        }
                    } else if (c.ValueType == typeof(byte[])) {
                        lut.Add(c.Name, basePath + "\\" + c.Name.Replace('.', '_'));
                    }
                    colnames += c.Name + sep;
                    headline += sep;
                }
                colnames = colnames.Remove(colnames.LastIndexOf(sep));
                headline = headline.Remove(headline.LastIndexOf(sep));
                sw.WriteLine(headline);
                sw.WriteLine(colnames);


                //Create Directories for BLOBS
                if (!excludeBLOBs) {
                    foreach (String c in lut.Values) {
                        Directory.CreateDirectory(c);
                    }
                }
                //Save BLOBS
                List<Spectrum> esl_spectra = new List<Spectrum>();
                foreach (DataGridViewColumn c in this.DGV.Columns) {
                    int idx = c.Index;
                    Type ct = c.GetType();
                    if(c is DataGridViewSpectrumColumn && lut.Keys.Contains<String>(c.Name)) {
                        foreach (DataGridViewRow r in this.DGV.Rows) {
                            if ((rBt_all.Checked || rB_selected.Checked && r.Selected) &&
                               !r.IsNewRow) {
                                   DataGridViewSpectrumCell SC = (DataGridViewSpectrumCell)r.Cells[c.Index];
                                Spectrum S = SC.getSpectrum();
                                Byte[] BA = (Byte[])SC.Value;
                                if (BA != null) {
                                    if (ASD_Reader.isValidASDSpectrum( BA)) {
                                        String path = String.Format("{0}\\id{1}.{2}", lut[c.Name], r.Index, "asd");
                                        File.WriteAllBytes(path, BA);
                                    } else {
                                        esl_spectra.Add(S);
                                    }
                                }
                            }
                        }
                    } 

                }
                //Write ESL-Spectra
                ESL_Writer ESLW = new ESL_Writer();
                String p_esl = basePath + "\\ESLs";
                Directory.CreateDirectory(p_esl);
                ESLW.createESLFiles(new FileInfo(String.Format("{0}\\spectra.sli", p_esl)), esl_spectra);

                //Write Rows into csv-Table
                foreach (DataGridViewRow row in this.DGV.Rows) {
                    if ((rBt_all.Checked || rB_selected.Checked && row.Selected) && !isEmptyRow(row) && !row.IsNewRow) {
                        rowstring = "";
                        String rowid = "";
                        if (id_columns.Count > 0) {
                            foreach (String c in id_columns) {
                                rowid += "_" + row.Cells[c].Value.ToString();
                            }
                        } else {
                            rowid = row.Index.ToString();
                        }
                        foreach (DataGridViewColumn dc in this.DGV.Columns) {
                            String thisname = "";//the value within the CSV Column
                            DataGridViewCell CELL = row.Cells[dc.Name];
                            if (!(CELL.Value == null || CELL.Value == DBNull.Value)) {
                                if(CELL is DataGridViewSpectrumCell) {
                                    DataGridViewSpectrumCell sc = (DataGridViewSpectrumCell)CELL;
                                    thisname = "<Spectrum " + rowid + ">";
                                }else if(CELL is DGVExtensions.DataGridViewByteArrayCell) {
                                    DataGridViewByteArrayCell sc = (DataGridViewByteArrayCell)CELL;
                                    thisname = "<File " + rowid + ">";
                                }else if(CELL is DGVExtensions.DataGridViewPhotoCell) {
                                    DGVExtensions.DataGridViewPhotoCell sc = (DGVExtensions.DataGridViewPhotoCell)CELL;
                                    thisname = "<Image " + rowid + ">";
                                } else if(CELL is DGVExtensions.DataGridViewGeometryCell) {
                                    DGVExtensions.DataGridViewGeometryCell sc = (DGVExtensions.DataGridViewGeometryCell)CELL;
                                    this.Name = sc.FormattedValue.ToString();
                                } else { //Normal Text-Column
                                    thisname = row.Cells[dc.Name].Value.ToString();
                                }
                            }
                            rowstring += thisname + sep;
                        }
                        rowstring = rowstring.Remove(rowstring.LastIndexOf(sep));
                        sw.WriteLine(rowstring);
                    }
                }
                this.DialogResult = DialogResult.OK;
                this.Close();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                sw.Flush();
                sw.Close();
                
            }
        }


        private bool isEmptyRow(DataGridViewRow row){
            foreach (DataGridViewCell cell in row.Cells) {
                if (!(cell.Value == null || cell.Value.ToString().Length==0)) return false;
            }
            return true;
        }
    }
}
